package ca.bcit.comp3910;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import ca.bcit.comp3910.access.EmployeeManager;
import ca.bcit.comp3910.access.TimesheetManager;

/**
 * View class to interact between the Login and the JSF
 * 
 * @author Ivy Cheung, Stacy Mitchell
 * @version 2.0
 */
@SuppressWarnings("serial")
@Named
@SessionScoped
public class Login implements Serializable {
    /**
     * Inject Employee Manager
     */
    @Inject
    private EmployeeManager em;
    /**
     * Inject Timesheet Manager
     */
    @Inject
    private TimesheetManager tm;
    /**
     * The Employee ID
     */
    private Integer empID;
    /**
     * The Employee Password
     */
    private String password;
    /**
     * Boolean to check if the login is invalid
     */
    private boolean invalidLogin = false;

    /** 
     * Getters and setters
     */
    public Integer getEmpID() { return empID; }
    public void setEmpID(Integer temp) { empID = temp; }

    public String getPassword() { return password; }
    public void setPassword(String temp) { password = temp; }

    public boolean isInvalidLogin() { return invalidLogin; }
	public void setInvalidLogin(boolean invalidLogin) {	this.invalidLogin = invalidLogin; }
	
	/**
     * Validates the login credentials.
     * 
     * @return string this is used to determine which page will be redirected
     *         next
     */
    public String login() {
        if (em.checkPassword(empID, password)) {
            if (em.isSuperUser(empID)) {
            	em.setEmployee(empID);
                return "superUser";
            } else if (!em.isSuperUser(empID)) {
            	tm.setViewTS(false);
            	tm.onCreate(empID);
                return "user";
            } else {
            	setInvalidLogin(true);
                return null;
            }
        }
        setInvalidLogin(true);
        return null;
    }

    /**
     * Logs out of session
     * @return login for redirection
     */
    public String logout(){
    	FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    	setEmpID(null);
    	setInvalidLogin(false);
    	return "login";
    }
}
